import sys
import shutil
import os
import curses
import re
import stat
import time
import subprocess

import utils
from settings import *
import settings
import section


def chdir(path: str) -> None:
    try:
        os.listdir(os.path.abspath(path))
        os.chdir(path)
    except PermissionError:
        return


def draw_ui():
    if settings.cause_stdcsr_clear:
        stdscr.clear()
        stdscr.refresh()
        left_update = True
        settings.cause_stdcsr_clear = False
    
    path_win.clear()

    cwd = os.getcwd().replace("\\", "/") + "/"
    total = \
        f"{username}@{hostname}:|{cwd}|{middle_section.selected}"[:curses.COLS - 2]

    total = total.split("|")

    path_win.addstr(0, 0, total[0], username_color | username_style)
    path_win.addstr(total[1], directory_color | directory_style)
    path_win.addstr(total[2], file_color | file_style)

    path_win.refresh()

    status_bar_win.clear()

    status_bar_str = \
        f"{middle_section.selected_index + 1}/{len(middle_section.entries)}"

    status_bar_win.addstr(
        0, status_bar_win_width - len(status_bar_str) - 1,
        status_bar_str
    )

    status_bar_win.refresh()

    middle_section.update()
    middle_section.draw(update_left_section=settings.left_update)

    command_win.clear()
    command_win.refresh()


def enter_command(x: int, y: int, char: str) -> str:
    stdscr.nodelay(False)
    curses.echo()
    curses.curs_set(True)

    # stdscr.move(y, x)

    # stdscr.addstr(":")

    # command = stdscr.getstr().decode("utf8")
    
    # stdscr.move(y, 0)

    command_win.addstr(char)
    command = command_win.getstr().decode("utf-8")

    #print("          ", end="")

    stdscr.nodelay(True)
    curses.noecho()
    curses.curs_set(False)

    return command


left_section = section.LeftSection(1, 1, curses.COLS / 4 - 2, curses.LINES - 4)
middle_section = section.Section(curses.COLS / 4 + 1, 1, curses.COLS / 4 - 2, curses.LINES - 4)
right_section = section.RightSection(curses.COLS / 2, 1, curses.COLS / 2 - 2, curses.LINES - 4)

middle_section.update()

path_win = curses.newwin(1, curses.COLS - 1, 0, 0)
command_win = curses.newwin(1, curses.COLS - 1, curses.LINES - 1, 0)
status_bar_win = curses.newwin(1, curses.COLS - 1, curses.LINES - 2, 0)
status_bar_win_width = curses.COLS - 1

#top_section = Section(1, 1, terminal_size[0], 1, "path")

# Clear terminal.
stdscr.clear()
stdscr.refresh()

#listener = keyboard.Listener(on_press=on_press)
#listener.start()

draw_ui()

while run:
    #print(run)
    
    #stdscr.move(0, 0)

    find_session = 0
    
    key = stdscr.getch()
    if key == -1:
        continue

    elif key == ord(":"):
        command = enter_command(0, terminal_size[1] - 1, ":")
        if command == "q":
            run = False

        elif command.startswith("cd"):
            args = command.split()[1:]
            chdir(args[0])

        elif command == "gg":
            middle_section.set_selected_index(0)

        elif command == "G":
            middle_section.set_selected_index(
                len(middle_section.entries) - 1
            )

    elif key == ord("/"):
        find_session = True
        find_command = enter_command(0, curses.LINES - 1, "/")

        r = re.compile(f"{find_command}")
        find_list = list(filter(r.match, middle_section.entries))

        find_number = 0

        if find_number < 0:
            find_number = len(find_list) - 1

        elif find_number > len(find_list):
            find_number = 0

        f = find_list[find_number]

        middle_section.set_selected_index(
            middle_section.entries.index(f)
        )

    elif key == ord("n") and find_number != -1:
        find_session = True
        print(find_number)
        find_number += 1
        
        if find_number < 0:
            find_number = len(find_list) - 1

        elif find_number >= len(find_list):
            find_number = 0

        f = find_list[find_number]

        middle_section.set_selected_index(
            middle_section.entries.index(f)
        )

    elif key == ord("N") and find_number != -1:
        find_session = True
        print(find_number)
        find_number -= 1
        
        if find_number < 0:
            find_number = len(find_list) - 1

        elif find_number >= len(find_list):
            find_number = 0

        f = find_list[find_number]

        middle_section.set_selected_index(
            middle_section.entries.index(f)
        )

    elif key == curses.KEY_LEFT:
        volume = False
        if sys.platform.startswith("win"):
            volume = re.fullmatch(".:/", os.getcwd().replace("\\", "/"))

        if not volume:
            chdir("..")
            right_section.update(middle_section.selected)
            middle_section.selected = left_section.selected
            left_update = True

    elif key == curses.KEY_RIGHT:
        if os.path.isdir(middle_section.selected):
            chdir(middle_section.selected)
            middle_section.selected = right_section.selected
            right_section.update(right_section.prev_selected)
            left_update = True

    elif key == curses.KEY_UP:
        middle_section.set_selected_index(
            middle_section.selected_index - 1
        )
        left_update = False
    
    elif key == curses.KEY_DOWN:
        middle_section.set_selected_index(
            middle_section.selected_index + 1
        )
        left_update = False

    if not find_session:
        find_list.clear()
        find_number = -1

    draw_ui()

    # stdscr.clrtoeol()
    #stdscr.clear()
    # stdscr.refresh()

# Deinitilize curses session.
curses.echo()
curses.nocbreak()
curses.curs_set(True)
stdscr.keypad(False)

# End curses session and clear terminal.
curses.endwin()

